# -*- coding: utf-8 -*-
#
# Copyright (C) 2009 Trevor R.H. Clarke <retrev@csh.rit.edu>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
# --
#
# File: die.py
# Author: Trevor R.H. Clarke <retrev@csh.rit.edu>
#
# Description: Die roller robot
#



import re
from waveapi import events,model,robot,document
import logging
import orpg.dieroller.utils

DiceManager = orpg.dieroller.utils.roller_manager()
DiceManager.setRoller('std')
dicereg = re.compile("dr:\[([^]]*?)\]")

def OnRobotAdded(properties, context):
   """Invoke when the robot has been added to a wave."""
   root_Wavelet = context.GetRootWavelet()

def OnBlipSubmitted(properties, context):
   """Scan the wave for die roll strings and replace with results."""
   blip = context.GetBlipById(properties['blipId'])
   blipDoc = blip.GetDocument()
   text = blipDoc.GetText()
   m = dicereg.search(text)
   while m is not None:
      try:
         roll_result = DiceManager.proccessRoll(m.group(1))
         blipDoc.DeleteRange(document.Range(m.start(), m.end()))
         blipDoc.InsertText(m.start(), "[%s] ==> %s" % (m.group(1),roll_result))

      except Exception,r:
         logging.error("EXCEPTION! %r" % r)
      m = dicereg.search(text, m.end())

if __name__ == '__main__':
   myRobot = robot.Robot('OpenRPG die roller',
      image_url='http://wave-openrpg.appspot.com/icon.png',
      profile_url='http://wave-openrpg.appspot.com/',
      version='1')
   myRobot.RegisterHandler(events.WAVELET_SELF_ADDED, OnRobotAdded)
   myRobot.RegisterHandler(events.DOCUMENT_CHANGED, OnBlipSubmitted)
   myRobot.Run()
